import axios from 'axios'
import Qs from 'qs'
// import Globals from '/components/Globals'
import { setStorage, getStorage } from '../utils/storage'
axios.defaults.timeout = 50000
axios.defaults.baseURL = process.env.VUE_APP_DATA_API_HOST + ''

// http request 拦截器
axios.interceptors.request.use(
  config => {
    config.headers['Accept'] = 'application/json'
    // if (location.href.indexOf('/login') > -1 || config.url === '/token') {
    //   return config
    // }
    // // 判断是否存在token，即判断用户是否登录，如果存在的话，则每个http header都加上token
    // let token = getStorage(Globals.AccessToken)
    // if (token) {
    //   //验证token是否过期
    //   // 用户每次操作，都将token过期时间设置成60分钟
    //   setStorage(Globals.AccessToken, token, Globals.ExpireTime)
    //   // 每个http header都加上token
    //   config.headers.Authorization = 'Bearer ' + token
    // } else {
    //   // 跳转登录
    //   location.href = '/login'
    // }
    return config
  },
  error => {
    return Promise.reject(error.response)
  }
)

// **路由响应拦截**
// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // let response = error.response
    // if (response.status === 401) {
    //   store.commit('loginOut')
    //   location.href = '/login'
    // } else {
    //   return Promise.reject(error.response) // 返回接口返回的错误信息
    // }
    return Promise.reject(error.response) // 返回接口返回的错误信息
  }
)

const fetchGet = (url, params) => {
  url = url + '?' + Qs.stringify(params)
  return new Promise((resolve, reject) => {
    axios.get(url).then(res => {
      resolve(res.data)
    }).catch(error => {
      reject(error)
    })
  })
}
const fetchPost = (url, params = {}, contentType='application/json') =>{
  return new Promise((resolve, reject) => {
    if (contentType === 'application/x-www-form-urlencoded') {
      params = Qs.stringify(params)
    }
    axios.post(url, params, {headers: {'Content-Type': contentType}}).then(res => {
      resolve(res.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export default {
  fetchGet,
  fetchPost,
  fetchPostExport (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, params, {responseType: 'blob'}).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  fetchPostFile (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(url, params, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}
